var express = require('express')
var router = express.Router()
const multer = require('multer')
const iconv = require('iconv-lite')
const path = require('path')
const fs = require('fs')

// 配置 multer 存储选项
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const filaname = getDecodedName(file.originalname)
    const stage = filaname.split('-')[0] || ''
    const name = filaname.split('-')[1] || ''
    let filePath = 'H:/Projects/我的工具库/考核管理平台/小组资源/'

    if (stage) {
      filePath += `${stage}/`
      if (name) {
        filePath += `${name}/`
      }
    }

    // 指定上传文件的目标目录
    cb(null, filePath)
  },
  filename: function (req, file, cb) {
    // 保留原始文件名
    // 你可以根据需要添加逻辑来处理文件名冲突或进行其他操作
    cb(null, getDecodedName(file.originalname))
  }
})

// 创建 multer 实例
const upload = multer({ storage: storage })

const getDecodedName = (originalname) => {
  // 假设 req.file.originalname 是乱码的原始文件名
  const originalnameBuffer = Buffer.from(originalname, 'binary') // 从 Multer 获取到的原始文件名通常是二进制格式的

  // 尝试将文件名从原始编码（如果已知）转换为 UTF-8
  // 如果文件名原本就是 UTF-8 编码的，则不需要转换
  const decodedName = iconv.decode(originalnameBuffer, 'utf8')
  return decodedName
}

// 单文件上传
router.post('/', upload.single('file'), (req, res) => {
  const response = {
    message: '',
    success: false,
    filePath: ''
  }
  if (!req.file) {
    return res.status(400).send('No file uploaded.')
  }
  response.success = true
  response.message = '上传成功'
  response.filePath = req?.file?.path
  console.log(req.file)
  // 更新data.json
  let data = fs.readFileSync(path.resolve(__dirname, '../data/data.json'), 'utf8')
  const stage = req.file.filename.split('-')[0] || ''
  const name = req.file.filename.split('-')[1] || ''
  data = JSON.parse(data)
  data.files[stage][name].resources = [req.file.path]
  console.log('data', data)
  fs.writeFileSync(path.resolve(__dirname, '../data/data.json'), JSON.stringify(data))
  res.send(JSON.stringify(response))
})

module.exports = router
